package cn.lzc.jl.service.conf.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.lzc.jl.service.util.codec.DES3Helper;
import cn.lzc.jl.service.util.codec.RequestDecode;

/**
 * 
 * <返回数据加密>
 * <功能详细描述>
 * 
 * @author  sunliang
 * @version  [版本号, 2018年8月31日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
@SuppressWarnings("rawtypes")
@ControllerAdvice(basePackages = "cn.lzc.jl.rest.test")
public class ResponseBodyAdviceHandle implements ResponseBodyAdvice
{
    private final static Logger logger = LoggerFactory.getLogger(ResponseBodyAdviceHandle.class);
    
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass,
        ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse)
    {
        boolean encode = false;
        if (methodParameter.getMethod().isAnnotationPresent(RequestDecode.class))
        {
            //获取注解配置的包含和去除字段
            RequestDecode serializedField = methodParameter.getMethodAnnotation(RequestDecode.class);
            //出参是否需要加密
            encode = serializedField.outEncode();
        }
        if (encode)
        {
            logger.info("method :【" + methodParameter.getMethod().getName() + "】返回数据加密");
            ObjectMapper objectMapper = new ObjectMapper();
            try
            {
                String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
                return DES3Helper.encrypt(result);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                logger.error("method :【" + methodParameter.getMethod().getName() + "】返回数据解密出现异常：" + e.getMessage());
            }
        }
        return body;
    }
    
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass)
    {
        return true;
    }
    
}
